import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Switch,
  TextInput,
  Alert,
  ActivityIndicator
} from 'react-native';
import { useSelector, useDispatch } from 'react-redux';
import { 
  setInterval,
  setSpeed,
  setAutoStart,
  setPerformanceMode,
  selectSettings,
  resetSettings
} from '../../store/slices/autoScrollSlice';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { SETTINGS_CONFIG } from '../../utils/constants';

const SettingsScreen = () => {
  const dispatch = useDispatch();
  const settings = useSelector(selectSettings);
  
  const [loading, setLoading] = useState(false);
  const [customInterval, setCustomInterval] = useState(settings.interval.toString());
  const [exporting, setExporting] = useState(false);

  // 处理间隔设置
  const handleIntervalChange = (value) => {
    const numValue = parseInt(value);
    if (numValue >= 1 && numValue <= 30) {
      dispatch(setInterval(numValue));
    }
  };

  // 处理速度设置
  const handleSpeedChange = (speed) => {
    dispatch(setSpeed(speed));
  };

  // 处理自动启动设置
  const handleAutoStartChange = (value) => {
    dispatch(setAutoStart(value));
  };

  // 处理性能模式设置
  const handlePerformanceModeChange = (value) => {
    dispatch(setPerformanceMode(value));
  };

  // 重置设置
  const handleResetSettings = () => {
    Alert.alert(
      '重置设置',
      '确定要重置所有设置到默认值吗？',
      [
        { text: '取消', style: 'cancel' },
        { 
          text: '确定', 
          onPress: () => {
            dispatch(resetSettings());
            setCustomInterval(SETTINGS_CONFIG.DEFAULT_INTERVAL.toString());
            Alert.alert('成功', '设置已重置到默认值');
          }
        }
      ]
    );
  };

  // 导出设置
  const handleExportSettings = async () => {
    try {
      setExporting(true);
      const settingsData = {
        settings,
        exportDate: new Date().toISOString(),
        version: '1.0'
      };
      
      const jsonData = JSON.stringify(settingsData, null, 2);
      
      // 这里可以集成文件保存功能
      console.log('导出设置:', jsonData);
      
      Alert.alert('成功', '设置已导出到日志');
    } catch (error) {
      console.error('导出设置失败:', error);
      Alert.alert('错误', '导出设置失败');
    } finally {
      setExporting(false);
    }
  };

  // 导入设置
  const handleImportSettings = async () => {
    Alert.alert(
      '导入设置',
      '此功能需要文件选择器支持',
      [
        { text: '取消', style: 'cancel' },
        { 
          text: '确定', 
          onPress: () => {
            // 这里可以集成文件选择器
            Alert.alert('提示', '请实现文件选择功能');
          }
        }
      ]
    );
  };

  // 清除缓存
  const handleClearCache = async () => {
    try {
      setLoading(true);
      
      // 清除AsyncStorage中的缓存数据
      const keys = await AsyncStorage.getAllKeys();
      const cacheKeys = keys.filter(key => key.includes('cache_'));
      
      if (cacheKeys.length > 0) {
        await AsyncStorage.multiRemove(cacheKeys);
      }
      
      Alert.alert('成功', '缓存已清除');
    } catch (error) {
      console.error('清除缓存失败:', error);
      Alert.alert('错误', '清除缓存失败');
    } finally {
      setLoading(false);
    }
  };

  // 关于应用
  const handleAboutApp = () => {
    Alert.alert(
      '关于应用',
      '自动下滑翻视频 v1.0.0\n\n' +
      '一个智能的视频浏览助手应用，\n' +
      '支持多平台自动滑动浏览。\n\n' +
      '开发者：AI助手\n' +
      '版本：1.0.0\n' +
      '更新时间：2024年',
      [{ text: '确定' }]
    );
  };

  if (loading) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color="#4CAF50" />
        <Text style={styles.loadingText}>正在处理...</Text>
      </View>
    );
  }

  return (
    <ScrollView style={styles.container}>
      <View style={styles.header}>
        <Text style={styles.title}>设置</Text>
        <Text style={styles.subtitle}>自定义您的使用体验</Text>
      </View>

      {/* 滑动设置 */}
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>滑动设置</Text>
        
        {/* 间隔设置 */}
        <View style={styles.settingItem}>
          <Text style={styles.settingLabel}>滑动间隔（秒）</Text>
          <View style={styles.intervalContainer}>
            <TextInput
              style={styles.intervalInput}
              value={customInterval}
              onChangeText={setCustomInterval}
              onBlur={() => handleIntervalChange(customInterval)}
              keyboardType="numeric"
              maxLength={2}
              placeholder="1-30"
            />
            <Text style={styles.intervalHint}>范围：1-30秒</Text>
          </View>
        </View>

        {/* 速度设置 */}
        <View style={styles.settingItem}>
          <Text style={styles.settingLabel}>滑动速度</Text>
          <View style={styles.speedContainer}>
            {[
              { key: 'slow', label: '慢速', description: '更自然的滑动' },
              { key: 'normal', label: '正常', description: '标准滑动速度' },
              { key: 'fast', label: '快速', description: '更快的滑动' }
            ].map((speed) => (
              <TouchableOpacity
                key={speed.key}
                style={[
                  styles.speedOption,
                  settings.speed === speed.key && styles.speedOptionSelected
                ]}
                onPress={() => handleSpeedChange(speed.key)}
              >
                <Text style={[
                  styles.speedLabel,
                  settings.speed === speed.key && styles.speedLabelSelected
                ]}>
                  {speed.label}
                </Text>
                <Text style={[
                  styles.speedDescription,
                  settings.speed === speed.key && styles.speedDescriptionSelected
                ]}>
                  {speed.description}
                </Text>
              </TouchableOpacity>
            ))}
          </View>
        </View>
      </View>

      {/* 高级设置 */}
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>高级设置</Text>
        
        {/* 自动启动 */}
        <View style={styles.settingItem}>
          <View style={styles.switchContainer}>
            <Text style={styles.settingLabel}>自动启动</Text>
            <Text style={styles.settingDescription}>应用启动时自动开始滑动</Text>
          </View>
          <Switch
            value={settings.autoStart}
            onValueChange={handleAutoStartChange}
            trackColor={{ false: '#767577', true: '#4CAF50' }}
            thumbColor={settings.autoStart ? '#4CAF50' : '#f4f3f4'}
          />
        </View>

        {/* 性能模式 */}
        <View style={styles.settingItem}>
          <View style={styles.switchContainer}>
            <Text style={styles.settingLabel}>性能模式</Text>
            <Text style={styles.settingDescription}>优化内存和CPU使用</Text>
          </View>
          <Switch
            value={settings.performanceMode}
            onValueChange={handlePerformanceModeChange}
            trackColor={{ false: '#767577', true: '#4CAF50' }}
            thumbColor={settings.performanceMode ? '#4CAF50' : '#f4f3f4'}
          />
        </View>
      </View>

      {/* 数据管理 */}
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>数据管理</Text>
        
        <TouchableOpacity style={styles.actionButton} onPress={handleExportSettings}>
          <Text style={styles.actionButtonText}>
            {exporting ? '导出中...' : '导出设置'}
          </Text>
        </TouchableOpacity>
        
        <TouchableOpacity style={styles.actionButton} onPress={handleImportSettings}>
          <Text style={styles.actionButtonText}>导入设置</Text>
        </TouchableOpacity>
        
        <TouchableOpacity style={styles.actionButton} onPress={handleClearCache}>
          <Text style={styles.actionButtonText}>清除缓存</Text>
        </TouchableOpacity>
        
        <TouchableOpacity style={[styles.actionButton, styles.dangerButton]} onPress={handleResetSettings}>
          <Text style={[styles.actionButtonText, styles.dangerButtonText]}>重置设置</Text>
        </TouchableOpacity>
      </View>

      {/* 关于 */}
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>关于</Text>
        
        <TouchableOpacity style={styles.actionButton} onPress={handleAboutApp}>
          <Text style={styles.actionButtonText}>关于应用</Text>
        </TouchableOpacity>
      </View>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5F5F5',
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5F5F5',
  },
  loadingText: {
    marginTop: 16,
    fontSize: 16,
    color: '#666',
  },
  header: {
    backgroundColor: '#4CAF50',
    padding: 24,
    paddingTop: 40,
    alignItems: 'center',
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#FFFFFF',
    marginBottom: 4,
  },
  subtitle: {
    fontSize: 14,
    color: '#E8F5E8',
  },
  section: {
    backgroundColor: '#FFFFFF',
    marginHorizontal: 16,
    marginVertical: 8,
    borderRadius: 12,
    padding: 16,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 3.84,
    elevation: 5,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 16,
  },
  settingItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: '#F0F0F0',
  },
  settingLabel: {
    fontSize: 16,
    color: '#333',
    fontWeight: '500',
  },
  settingDescription: {
    fontSize: 12,
    color: '#666',
    marginTop: 2,
  },
  intervalContainer: {
    alignItems: 'flex-end',
  },
  intervalInput: {
    borderWidth: 1,
    borderColor: '#DDD',
    borderRadius: 8,
    paddingHorizontal: 12,
    paddingVertical: 8,
    fontSize: 16,
    textAlign: 'center',
    minWidth: 60,
  },
  intervalHint: {
    fontSize: 12,
    color: '#666',
    marginTop: 4,
  },
  speedContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  speedOption: {
    flex: 1,
    backgroundColor: '#F5F5F5',
    padding: 12,
    borderRadius: 8,
    marginHorizontal: 4,
    alignItems: 'center',
  },
  speedOptionSelected: {
    backgroundColor: '#4CAF50',
  },
  speedLabel: {
    fontSize: 14,
    color: '#666',
    fontWeight: 'bold',
    marginBottom: 4,
  },
  speedLabelSelected: {
    color: '#FFFFFF',
  },
  speedDescription: {
    fontSize: 11,
    color: '#999',
    textAlign: 'center',
  },
  speedDescriptionSelected: {
    color: '#E8F5E8',
  },
  switchContainer: {
    flex: 1,
  },
  actionButton: {
    backgroundColor: '#4CAF50',
    paddingHorizontal: 16,
    paddingVertical: 12,
    borderRadius: 8,
    marginVertical: 4,
    alignItems: 'center',
  },
  actionButtonText: {
    color: '#FFFFFF',
    fontSize: 14,
    fontWeight: 'bold',
  },
  dangerButton: {
    backgroundColor: '#FF4444',
  },
  dangerButtonText: {
    color: '#FFFFFF',
  },
});

export default SettingsScreen;